package com.haixiaoke.smartLock.haixiaoke;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.aliyun.oss.ClientConfiguration;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.OSSObject;
import com.haixiaoke.common.oss.config.OssConfig;
import com.haixiaoke.common.oss.service.OSSService;
import com.haixiaoke.common.utils.sign.AesUtils;
import com.haixiaoke.domain.LockUnlockLog;
import com.haixiaoke.domain.LockWarningLog;
import com.haixiaoke.mapper.SmartLockFingerprintMapper;
import com.haixiaoke.service.*;
import com.haixiaoke.vo.HxkDataVO;
import com.haixiaoke.vo.HxkWarnVO;
import com.haixiaoke.vo.YltDataVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.entity.ContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author panda
 * @Date 2023/10/19
 **/
@Slf4j
@Service
public class SmartLockHxkLogEventHandleService {

    @Autowired
    private ILockUnlockLogService lockUnlockLogService;
    @Autowired
    private ILockWarningLogService lockWarningLogService;
    @Autowired
    private OSSService ossService;
    @Autowired
    private SmartLockHXKService smartLockHXKService;

    public void logEventHandle(List<Map<String, Object>> list) {
        Date date = new Date();
        for (Map<String, Object> map : list) {
            // map转对象
            HxkDataVO hxkDataVO = BeanUtil.fillBeanWithMap(map, new HxkDataVO(), false);

            LockUnlockLog log = new LockUnlockLog();
            log.setLockSn(hxkDataVO.getDeviceMac());
            String openType = hxkDataVO.getOpenType();
            // 将开锁状态转换为系统开锁类型
            log.setUnlockType(hxkOpenTypeConvert(openType));
            log.setUnlockState(0);
            log.setUnlockTime(DateUtil.parse(hxkDataVO.getOpenTime()));
            log.setIdentification(hxkDataVO.getIdNumber());
            log.setBrandId(LockWarningLog.HXK_BRAND_ID);
            log.setLockState(LockUnlockLog.LOCK_STATE_ONLINE);
            log.setBrandName(LockWarningLog.HXK_BRAND_NAME);
            log.setModelId(LockWarningLog.HXK_BRAND_MODEL_ID);
            log.setModelName(LockWarningLog.HXK_BRAND_MODEL_NAME);
            log.setCreateTime(date);
            lockUnlockLogService.insertLockUnlockLog(log);
        }
    }

    private Integer hxkOpenTypeConvert(String openType) {

        // 开门类型，固定为0x01人脸，0x02指纹，0x03密码，0x04卡，0x05临时密码,0x06远程开门，0x07胁迫报警）
        /**
         * 系统开锁类型:1：永久密码 2：指纹 3：临时密码 4：远程开锁 5：蓝牙开锁 6：cookie开锁 7：门卡开锁
         * 8- 撤防/布防 10：机械钥匙开门 11：反锁 12 - 门内开锁 13:装修密码 14:装修密码开锁失败 15:离线开锁 16:人脸开锁 17:胁迫报警
         */
        Integer type = null;
        switch (openType) {
            case "01":
                type = 16;
                break;
            case "02":
                type = 2;
                break;
            case "03":
                type = 3;
                break;
            case "04":
                type = 7;
                break;
            case "05":
                type = 15;
                break;
            case "06":
                type = 4;
                break;
            case "07":
                type = 17;
                break;
        }
        return type;
    }

    @Autowired
    private OssConfig ossConfig;

    public void warnEventHandle(List<Map<String, Object>> list) {
        Date date = new Date();
        for (Map<String, Object> map : list) {
            // map转对象
            HxkWarnVO hxkWarnVO = BeanUtil.fillBeanWithMap(map, new HxkWarnVO(), false);

            Integer openType = null;
            switch (hxkWarnVO.getPhotoType()){
                case "0C":
                    openType = 1;
                case "0B":
                    openType = 16;
                case "0D":
                    openType = 7;
            }
            if (ObjectUtil.isNull(openType)) {
                continue;
            }


            byte[] bytes = smartLockHXKService.getOpenImage(hxkWarnVO.getPhotoUrl());
            long l = System.currentTimeMillis() + RandomUtils.nextInt(1000, 10000);
//            https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/ad/202103241616570837695.jpg
            String imageUrl = "";
            if (bytes != null) {

                InputStream inputStream = new ByteArrayInputStream(bytes);

                try {
                    MultipartFile file = new MockMultipartFile(String.valueOf(l), l+".jpg","", inputStream);
                    imageUrl = ossService.putFile(null, file, "ad");
                    /*File temp = new File( file.getOriginalFilename());
                    try (FileOutputStream fos = new FileOutputStream(temp);
                         BufferedOutputStream bos = new BufferedOutputStream(fos)) {
                        bos.write(file.getBytes());
                        bos.flush();
                    }

                    StringBuilder fileKey = new StringBuilder();
                    fileKey.append("ad/").append(file.getOriginalFilename());
//                    imageUrl = imageUrl + fileKey;
                    // 上传
                    OSSClient ossClient = new OSSClient(ossConfig.getEndpoint(), ossConfig.getAccessKeyId(), ossConfig.getAccessKeySecret());
                    ossClient.putObject("xj-saas-images", fileKey.toString(), temp);
                    imageUrl =  "https://xj-saas-images.oss-cn-qingdao.aliyuncs.com/" + fileKey;*/
                }catch (Exception e){
                    log.error("嗨小克--抓拍回调操作文件流异常：{}", e.getMessage(), e);
                    throw new RuntimeException(e);
                }

            }

            String recordId = hxkWarnVO.getLinkedOpenRecordId();
            int i = Integer.parseInt(recordId);
            if (i >0) {
                LockUnlockLog log = new LockUnlockLog();
                log.setLockSn(hxkWarnVO.getDeviceMac());
                // 将开锁状态转换为系统开锁类型
                log.setUnlockType(openType);
                log.setUnlockState(1);
                log.setUnlockTime(DateUtil.parse(hxkWarnVO.getPhotoTime()));
                log.setBrandId(LockWarningLog.HXK_BRAND_ID);
                log.setBrandName(LockWarningLog.HXK_BRAND_NAME);
                log.setModelId(LockWarningLog.HXK_BRAND_MODEL_ID);
                log.setModelName(LockWarningLog.HXK_BRAND_MODEL_NAME);
                log.setCreateTime(date);
                log.setOpenImage(imageUrl);

                lockUnlockLogService.insertLockUnlockLog(log);
            } else {
                LockWarningLog log = new LockWarningLog();
                log.setLockSn(hxkWarnVO.getDeviceMac());
                log.setWarningType(8);
                log.setCreateTime(DateUtil.parse(hxkWarnVO.getPhotoTime()));
                log.setBrandId(LockWarningLog.HXK_BRAND_ID);
                log.setBrandName(LockWarningLog.HXK_BRAND_NAME);
                log.setModelId(LockWarningLog.HXK_BRAND_MODEL_ID);
                log.setModelName(LockWarningLog.HXK_BRAND_MODEL_NAME);
                log.setWarningImage(imageUrl);
                lockWarningLogService.insertLockWarningLog(log);
            }

        }
    }
}
